var $table = $("#table_sensor");
var $add=$("#add_button");
var $edit=$("#edit_button");
var $search=$("#search_button");
// $("#incomegrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "scroll" });
$(document).ready(function () {
    $.jgrid.defaults.styleUI = 'Bootstrap';
    $table
        .jqGrid({
            mtype:"post",
            url:"/sensor/data",
            datatype: "json",//为local时初始化不加载，支持json，xml等
            height: 350,
            autowidth: true,
            autoScroll: false,
            shrinkToFit: false,//此属性用来说明当初始化列宽度时候的计算类型，如果为ture，则按比例初始化列宽度。如果为false，则列宽度使用colModel指定的宽度
            rowNum: 10,//每页记录数
            rowList: [10, 20, 30],//每页记录数可选列表
            loadonce:true,//一次性加载所有数据，用于前端分页
            colNames: ['传感器序号', '传感器类别', '传感器名称', '英文名称', '物理量数','物理量一','物理量二','物理量三','传感器原理','精确度','效率时间','传感器应用','传感器限制','传感器重量','传感器宽度','传感器原料','花费时间','花费金钱',"操作"],//表头
            colModel: [//这里会根据index去解析jsonReader中root对象的属性，填充cell
                {name: 'sensoId', index: 'sensoId', width: 90, sorttype: "int"},
                {name: 'sensoCategory', index: 'sensoCategory', width: 120},
                {name: 'sensoName', index: 'sensoName', width: 150},
                {name: 'nameEngli', index: 'nameEngli', width: 150},
                {name: 'physiCount', index: 'physiCount', width: 30, sorttype: "int"},
                {name: 'physiQuantity1', index: 'physiQuantity1', width: 70},
                {name: 'physiQuantity2', index: 'physiQuantity2', width: 70},
                {name: 'physiQuantity3', index: 'physiQuantity3', width: 70},
                {name: 'sensoPrinc', index: 'sensoPrinc', width: 120},
                {name: 'sensoAccur', index: 'sensoAccur', width: 90},
                {name: 'efficTime', index: 'efficTime', width: 90},
                {name: 'sensoAppli', index: 'sensoAppli', width: 90},
                {name: 'sensoLimit', index: 'sensoLimit', width: 90},
                {name: 'sensoWeigh', index: 'sensoWeigh', width: 90},
                {name: 'sensoVolum', index: 'sensoVolum', width: 90},
                {name: 'sensoMater', index: 'sensoMater', width: 90},
                {name: 'costTime', index: 'costTime', width: 90},
                {name: 'costMoney', index: 'costMoney', width: 90},
                {name: '操作', label: '操作',width: 120,frozen:true,
                    formatter:
                        function(cellvalue, options, row){
                            return"<a style='margin:2px' class=\'btn btn-primary btn-sm \' href=\'#\' title=\'编辑\'>" +
                                "<i class=\"fa fa-edit\">" +
                                "</i>" +
                                "</a>" +
                                "<a style='margin:2px' class=\"btn btn-danger btn-sm \" href=\"#\" title=\"删除\">" +
                                "<i class=\"fa fa-remove\">" +
                                "</i>" +
                                "</a>"
                        }
                }
            ],
            pager: "#pager_sensor",
            viewrecords: true,//显示记录数信息,默认显示为{0}-{1} 共{2}条
            caption: "表6",//显示查询结果表格标题
            hidegrid: false,
            multiselect: true,//多选框
            multiboxonly: true,
            toolbar: [true, "top"] //在点击表格row时只支持单选，只有当点击checkbox时才多选，需要multiselect=true是有效
        })
        .navGrid('#pager_sensor',{edit:false,add:false,del:false,search:false,refresh:false},{height:200});
    $("#t_table_sensor").append(
        "<div class=\"input-group\" style=\"float: left;width:240px;margin:0 2px\">\n" +
        "<input id=\"find_sensorid\" name=\"find_sensorid\" type=\"text\" class=\"form-control\"/>\n" +
        "<span class=\"input-group-btn\">\n" +
        "<button class=\"btn btn-success\" type=\"button\" onclick=\"layer.msg('未实现')\"><i aria-hidden=\"true\" class=\"fa fa-search\"></i>查询</button>\n" +
        "</span>\n" +
        "</div>" +
        "<div style=\"float:right;margin:0 2px\">" +
        "<button id=\"add\" type=\"button\" class=\"btn btn-warning\" onclick=\"addDlg()\"><i aria-hidden=\"true\" class=\"fa fa-plus\"></i>增加</button>"+
        "</div>" +
        "<div style=\"float:right;margin:0 2px\">" +
        "<button id=\"delete\" type=\"button\" class=\"btn btn-danger\" onclick=\"layer.msg('有点问题')\"><i aria-hidden=\"true\" class=\"fa fa-trash\"></i>删除</button>" +
        "</div>" +
        // "<div style=\"float:right;margin:0 2px\">" +
        // "<button id=\"edit\" type=\"button\" class=\"btn btn-warning\" onclick=\"editDlg()\"><i aria-hidden=\"true\" class=\"fa fa-edit\"></i>修改</button>" +
        // "</div>" +
        "<div style=\"float:right;margin:0 2px\">" +
        "<button id=\"refresh\" type=\"button\" class=\"btn btn-info\" onclick=\"refDlg()\"><i aria-hidden=\"true\" class=\"fa fa-refresh\"></i>刷新</button>" +
        "</div>"
    );

    $(window).bind('resize', function () {
        var width = $('.jqGrid_wrapper').width();
        $table.setGridWidth(width);
    });
});

function addDlg() {
    //调出modal的dialog表
    $("#addDlg").modal();
    $.ajax({
        url:"/sensor/max",
        type:"post",
        success:function(data) {
            $('#addsensoId').val(data+1);
            //    .attr('readonly', true)
        }
    });
}
function validateAdd() {
    return $("#form_add").validate({
        rules: {
            sensoId: {
                required: true,
                digits: true
            },
            sensoCategory: {
                required: true
            },
            sensoName: {
                required: true
            },
            nameEngli: {
                required: true
            },
            physiCount: {
                required: true
            },
            physiQuantity1: {
                required: true
            }
        },
        messages: {
            sensoId: {
                required: "请输入id",
                digits: "id必须是整数！"
            },
            sensoCategory: {
                required: "请输入传感器类别！"
            },
            sensoName: {
                required: "请输入传感器名称！"
            },
            nameEngli: {
                required: "请输入英文名称！"
            },
            physiCount: {
                required: "请输入物理量数！"
            },
            physiQuantity1: {
                required: "请输入物理量一！"
            }
        }
    });
}
$add.click(function () {
    if(validateAdd().form()) {
        // layer.msg("通过验证！");
        save();
    } else {
        // layer.msg("请检查格式！");
    }
});
function save() {
    var form_data = $("#form_add").serialize();
    var b_data = decodeURIComponent(form_data, true);//防止中文乱码
    var userdata = DataDeal.formToJson(b_data);//转化为json
    $.ajax({
        type: "POST",
        url: "/sensor/save",
        contentType: "application/json;charset=utf-8",
        data: userdata,
        success: function (data) {
            layer.msg(data);
            reload();
            $('#addDlg').modal('hide').on("hidden", function () {
                $(this).removeData("modal");
            });
            document.getElementById("form_add").reset();//重置表单
        }
    });
}

function editDlg() {
    //调用方法
    var rowIds = $table.jqGrid('getGridParam', 'selarrrow');
    if(rowIds.length===1) {
        // console.log(rowIds[0]);
        $("#editDlg").modal();
        var rowid = $table.getGridParam("selrow");
        //调用方法getRowData，找到索引对应的行
        var row = $table.jqGrid('getRowData', rowid);
        //给元素赋值增加特性只读
        $('#editsensoId').val(row.sensoId).attr('readonly', true);
        $('#editsensoCategory').val(row.sensoCategory);
        $('#editsensoName').val(row.sensoName);
        $('#editnameEngli').val(row.nameEngli);
        $('#editphysiCount').val(row.physiCount);
        $('#editphysiQuantity1').val(row.physiQuantity1);
        $('#editphysiQuantity2').val(row.physiQuantity2);
        $('#editphysiQuantity3').val(row.physiQuantity3);
        $('#editsensoPrinc').val(row.sensoPrinc);
        $('#editsensoAccur').val(row.sensoAccur);
        $('#editefficTime').val(row.efficTime);
        $('#editsensoAppli').val(row.sensoAppli);
        $('#editsensoLimit').val(row.sensoLimit);
        $('#editsensoWeigh').val(row.sensoWeigh);
        $('#editsensoVolum').val(row.sensoVolum);
        $('#editsensoMater').val(row.sensoMater);
        $('#editcostTime').val(row.costTime);
        $('#editcostMoney').val(row.costMoney);
    }
    //调用layer界面，显示"请选择一行进行编辑！"
    else layer.msg("请选择一行进行编辑！");
}
function validateEdit() {
    return $("#form_edit").validate({
        rules: {
            sensoId: {
                required: true,
                digits: true
            },
            sensoCategory: {
                required: true
            },
            sensoName: {
                required: true
            },
            nameEngli: {
                required: true
            },
            physiCount: {
                required: true
            },
            physiQuantity1: {
                required: true
            }
        },
        messages: {
            sensoId: {
                required: "请输入id",
                digits: "id必须是整数！"
            },
            sensoCategory: {
                required: "请输入传感器类别！"
            },
            sensoName: {
                required: "请输入传感器名称！"
            },
            nameEngli: {
                required: "请输入英文名称！"
            },
            physiCount: {
                required: "请输入物理量数！"
            },
            physiQuantity1: {
                required: "请输入物理量一！"
            }
        }
    });
}
$edit.click(function () {
    if(validateEdit().form()) {
        edit();
    } else {
        // layer.msg("请检查格式！");
    }
});
function edit() {
    var form_data = $('#form_edit').serialize();
    var b_data = decodeURIComponent(form_data, true);//防止中文乱码
    var userdata = DataDeal.formToJson(b_data);//转化为json
    $.ajax({
        type: "post",
        url: "/sensor/edit",
        contentType: "application/json;charset=utf-8",
        data: userdata,
        success: function (data) {
            layer.msg(data);
            reload();
            $('#editDlg').modal('hide').on("hidden", function () {
                $(this).removeData("modal");
            });
            document.getElementById("form_edit").reset();//重置表单
        }
    });
}

function delDlg() {
    var rowIds = $table.jqGrid('getGridParam', 'selarrrow');
    layer.confirm("确认要删除选中的数据吗?", {
            btn : [ '确定', '取消' ]},
        function () {
            for(var i=0;i<rowIds.length;i++) {
                var rowid = rowIds[i];
                var row = $table.jqGrid('getRowData', rowid);
                var id = row.sensoId;
                $.ajax({
                    type: "post",
                    url: "/sensor/delete",
                    data: {"id": id},
                    dataType: "text",
                    success: function (data) {
                        layer.msg(data);
                        reload();
                        layer.closeAll('dialog');
                    }
                });
            }
        }
    );
}

function serDlg() {
    $("#searchDlg").modal();
    document.getElementById("search_input").value="";
}
// function validateSearchSensoId() {
//     return $("#form_search").validate({
//         rules: {
//             search_input: {
//                 digits: true
//             }
//         },
//         messages: {
//             search_input: {
//                 digits: "id必须是整数！"
//             }
//         }
//     });
// }
$search.click(function () {
    // var value = $("#search_select ").val();//获取select的值
    // if(value==="sensoId") {
    //     if(validateSearchSensoId().form()) {
    //         search();
    //     }
    // } else{
    //     search();
    // }
    search();
});
function search() {
    var value = $("#search_select ").val();
    console.info(value);
    var id = $("#search_input").val().replace(/(^\s*)|(\s*$)/g, "");//replace用于去掉首尾的空格
    console.info(id);
    if(id!==null&&id!==undefined&&id!=="") {
        $('#searchDlg').modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
        $table.jqGrid('clearGridData');
        $table.jqGrid('setGridParam', {  // 重新加载数据
            url: "/sensor/find/"+value,
            datatype: 'json',
            mtype: "post",
            postData: {"id": id}
        }).trigger("reloadGrid");
    }
    else {
        $("#searchDlg").modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
    }
}
//******************************************
function refDlg() {
    reload();
}
function reload() {
    $table.jqGrid('clearGridData');
    $table.jqGrid('setGridParam',{  // 重新加载数据,已经自动用了ajax？
        datatype:'json',
        mtype:"post",
        url:"/sensor/data"
    }).trigger("reloadGrid");
}